﻿#region

using System;
using System.Collections;
using System.Collections.Generic;

#endregion

namespace GGEditor.API.Utility.Algorithms
{
    public class Text
    {
        public static string Wrap(string text, int maxLength)
        {
            if (text == "")
                return "";

            text = text.Replace("\n", " \n ");

            Queue<string> words = new Queue<string>(text.Split(' ', '\t'));
            List<string> lines = new List<string>();
            List<string> currentLine = new List<string>();
            int currentLength = -1;

            foreach (string currentWord in words) {
                if (currentWord == "\n" || (currentLength + currentWord.Length) > maxLength) {
                    lines.Add(String.Join(" ", currentLine.ToArray()));
                    currentLine.Clear();
                    currentLength = -1;
                }

                if (currentWord != "\n") {
                    currentLine.Add(currentWord);
                    currentLength += 1 + currentWord.Length;
                }
            }

            if (currentLength > 0)
                lines.Add(String.Join(" ", currentLine.ToArray()));

            return String.Join("\n", lines.ToArray());
        }

        public static string ArrayToString(object[] array)
        {
            if (array == null || array.Length == 0)
                return "()";

            List<string> substrs = new List<string>();

            foreach (object o in array)
                substrs.Add(ArrayToString(o));

            return "(" + String.Join(", ", substrs.ToArray()) + ")";
        }

        private static string ArrayToString(object o)
        {
            if (o == null)
                return "null";

            if (o is string)
                return "\"" + (o as string) + "\"";

            if (o is IEnumerable)
                return ArrayToString(o);

            return o.ToString();
        }
    }
}